/* model */
import { 
  ConnectorCardInfo,
  ConnectorCardMultiFixedFieldNameEnum, 
  ConnectorCardMultiFixedFields, 
  ConnectorField, 
  ConnectorFieldTypeEnum, 
  ConnectorModuleComponentNameEnum 
} from '@src/modules/connector/model'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import TaskAddress from '@model/entity/TaskAddress'
/* hooks */
import { useConnectorCard } from '@src/modules/connector/hooks'
/* scss */
import '@src/modules/connector/components/connector-card/multi-card-table.scss'
/* vue */
import { ComponentInstance, defineComponent, PropType } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement, VNode } from 'vue'
/* service */
import { getFieldName, isSystemFiled } from '@service/FieldService'
/* util */
import { isArray, isElement, isNotArray } from '@src/util/type'
import { formatFormField } from '@src/filter/form'
import { isOpenData } from '@src/util/platform'
import { fmt_datetime } from '@src/filter/fmt'
/* types */
import { ConnectorServerValueCustomerType, ConnectorServerValueProductType, ConnectorServerValueRelatedCustomersType } from '@src/modules/connector/types'
import { FieldTypeMappingEnum, TaskFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
import { t } from '@src/locales'

export type ConnectorModuleConnectorCardMultiCardTableProps = {
  field: ConnectorField;
  loading: boolean;
  value: object;
  showDeleteButton: boolean;
  showIndex: boolean;
}

export interface ConnectorModuleConnectorCardMultiCardTableSetupState {
  
}

export enum ConnectorModuleConnectorCardMultiCardTableEmitEventNameEnum {
  Delete = 'delete',
}

export type ConnectorModuleConnectorCardMultiCardTableInstance = ComponentInstance & ConnectorModuleConnectorCardMultiCardTableSetupState
export type ConnectorModuleConnectorCardMultiCardTableVM = any // TODO 20221216From 15分支 ComponentRenderProxy<ConnectorModuleConnectorCardMultiCardTableProps> & CommonComponentInstance & ConnectorModuleConnectorCardMultiCardTableInstance

export default defineComponent({
  name: 'form-select-connector',
  emits: [
    ConnectorModuleConnectorCardMultiCardTableEmitEventNameEnum.Delete,
  ],
  props: {
    field: {
      type: Object as PropType<ConnectorField>,
      default: () => ({})
    },
    loading: {
      type: Boolean as PropType<boolean>,
      default: true
    },
    mainModuleValue: {
      type: Object as PropType<Record<string, any>>,
      default: () => ({})
    },
    value: {
      type: Object as PropType<Record<string, any>>,
      default: () => ({})
    },
    showDeleteButton: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    showIndex: {
      type: Boolean as PropType<boolean>,
      default: false
    },

  },
  setup(props: ConnectorModuleConnectorCardMultiCardTableProps, { emit }) {
    const onConnectorCardItemDeleteHandler = (row: Record<string, any>) => {
      emit(ConnectorModuleConnectorCardMultiCardTableEmitEventNameEnum.Delete, row)
    }

    return {
      onConnectorCardItemDeleteHandler,
    }
  },
  methods: {
    /** 
     * @description 渲染表格插入 用于无限加载显示
    */
    renderTableAppendSlot() {
      return (
        <div class={ this.loading ? 'block-hide' : 'block-show'}>
          <BaseListForNoData  notice-msg={t('common.base.tip.noData')}></BaseListForNoData>
        </div>
      )
    },
    /** 
     * @description 渲染表格列
    */
    renderTableColumnField(h: CreateElement, row: any, column: ConnectorField) {
      console.log('renderTableColumnField')
      // 渲染业务列
      const renderColumnWithBusinessValue = this.renderColumnWithBusiness(column, row)
      
      // 已经是元素 直接返回
      if (isElement(renderColumnWithBusinessValue)) {
        return renderColumnWithBusinessValue
      }
      
      return (
        <div class='biz-table-cell'>
          { renderColumnWithBusinessValue }
        </div>
      )
      
    },
    /**
     * @description: 渲染业务字段
     * @param {ConnectorField} column 列
     * @param {any} row 行数据
     * @return {VNode} 元素
     */ 
    renderColumnWithBusiness(column: ConnectorField, row: any): VNode | JSX.Element | string | null {
      
      // @ts-ignore
      const formType = column.formType || column.fieldType
      
      // 用户名
      if (column.fieldName == ConnectorCardMultiFixedFieldNameEnum.UserName) {
        
        const value = row[column.fieldName]
        const staffId = row.staffId
        
        return this.renderUserName(value, staffId)
      }
      
      // 编号
      if (formType == ConnectorFieldTypeEnum.SerialNumber || formType == TaskFieldNameMappingEnum.TaskNo) {
        return this.renderColumnWithSerialNumber(column, row)
      }
      
      // 客户
      if (formType == ConnectorFieldTypeEnum.Customer) {
        return this.renderColumnWithCustomer(column, row)
      }
      
      // 关联客户
      if (formType == ConnectorFieldTypeEnum.RelatedCustomers) {
        return this.renderColumnWithRelatedCustomers(column, row)
      }
      
      // 关联工单
      if (formType == ConnectorFieldTypeEnum.RelatedTask || formType == ConnectorFieldTypeEnum.RelationTask) {
        return this.renderColumnWithRelatedTasks(column, row)
      }
      
      // 产品
      if (formType == ConnectorFieldTypeEnum.Product) {
        return this.renderColumnWithProduct(column, row)
      }
      
      // 客户地址
      if (formType == ConnectorFieldTypeEnum.CustomerAddress) {
        return this.renderColumnWithCustomerAddress(column, row)
      }
      
      // 客户联系人
      if (formType == ConnectorFieldTypeEnum.Linkman) {
        return this.renderColumnWithCustomerLinkman(column, row)
      }
      
      // 服务部门
      if (column.fieldName == ConnectorFieldTypeEnum.Tags) {
        return this.renderTag(column, row)
      }
      
      // 地址
      if (formType == ConnectorFieldTypeEnum.Address) {
        return this.renderColumnWithAddress(column, row)
      }
      
      // 日期
      if (formType == ConnectorFieldTypeEnum.Date) {
        return this.renderColumnWithDateTime(column, row)
      }

      // 操作
      if (column.fieldName == ConnectorCardMultiFixedFieldNameEnum.Operation) {
        return this.renderOperation(row)
      }
      
      return this.renderColumnWithCommon(column, row)
    },
    /**
     * @description: 渲染通用字段
     * @param {ConnectorField} column 列
     * @param {any} row 行数据
     * @return {VNode} 元素
     */
    renderColumnWithCommon(column: ConnectorField, row: any): VNode {
      
      // 是否是系统字段
      const isSystem = isSystemFiled(column)
      // 字段类型
      const formType = column.formType || ''
      // 字段名称
      const fieldName = getFieldName(column)
      // 值
      const value = row[fieldName]
      
      return (
        <div>
          { formatFormField(column, row) }
        </div>
      )
      
    },
    /** 
     * @description 渲染 用户名
    */
    renderUserName(value: string, staffId: string) {
      
      const isShowOpenData = isOpenData && staffId
      
      return (
        <div>
          {isShowOpenData ? (
            <open-data type="userName" openid={staffId}></open-data>
          ) : (
            value
          )}
        </div>
      )
    },
    /* 人员类型 */
    renderColumnWithUser(column: ConnectorField, row: Record<string, any>): any {
      
      const user: LoginUser | any = row?.[column.fieldName || ''] || {}
      
      // 单选人员
      if(isOpenData && user.staffId) {
        return (<span><open-data type="userName" openid={user.staffId}></open-data></span>)
      }
      
      // 多选人员
      if (isOpenData && isArray(user)) {
        return (
          user.map((item: LoginUser) => {
            return <open-data type="userName" openid={item.staffId}></open-data>
          })
        )
      }
      
      return user?.displayName || user?.name || ''
    },
    /* 位置类型 */
    renderColumnWithLocation(column: ConnectorField, row: Record<string, any>): string {
      const location: Record<string, any> = row?.[column.fieldName || ''] || {}
      return location?.address || ''
    },
    /* 日期类型 */
    renderColumnWithDateTime(column: ConnectorField, row: Record<string, any>): string {
      
      const fieldName: string = column.fieldName || ''
      
      return fmt_datetime(row?.[fieldName])
    },
    /* 编号 */
    renderColumnWithSerialNumber(column: ConnectorField, row: Record<string, any>) {
      
      const serialNumber: number = row?.[column.fieldName || ''] || ''
      
      return (
        <div>
          { serialNumber }
        </div>
      )
      
    },
    /* 客户类型 */
    renderColumnWithCustomer(column: ConnectorField, row: Record<string, any>) {
      
      const customers = row?.[column.fieldName || ''] || []
      const customer = (
        isArray(customers) ? customers[0] || {} : customers
      ) || {}
      
      const classNames = 'view-detail-btn'
      
      const customerId = customer?.id || ''
      const customerName = customer?.name || ''
      
      return (
        <div>
          { customerName }
        </div>
      )
    },
    /* 产品类型 */
    renderColumnWithProduct(column: ConnectorField, row: Record<string, any>) {
      
      let products: ConnectorServerValueProductType[] = row?.[column.fieldName || ''] || []
      
      if (isNotArray(products)) {
        products = [products as unknown as ConnectorServerValueProductType]
      }
      
      const classNames = 'view-detail-btn'
      
      const content = products.map((item: ConnectorServerValueProductType) => {
        return (
          <div class="connector-card-multi-table-product-row-item">
            <div
              class={classNames}
            >
              { item.name }
            </div>
            <span class="connector-card-multi-table-product-row-text">
              ,
            </span>
          </div>
        )
      })
      
      return (
        <div class="connector-card-multi-table-product-row">
          { content }
        </div>
      )
    },
    /* 关联客户类型 */
    renderColumnWithRelatedCustomers(column: ConnectorField, row: Record<string, any>) {
      
      let customers: ConnectorServerValueRelatedCustomersType = row?.[column.fieldName || ''] || []
      
      if (isNotArray(customers)) {
        customers = [customers as unknown as ConnectorServerValueCustomerType]
      }
      
      const classNames = 'view-detail-btn'
      
      const content = customers.map((item: ConnectorServerValueCustomerType) => {
        return (
          <div class="connector-card-multi-table-customer-row-item">
            <div
              class={classNames}
            >
              { item.name }
            </div>
            <span class="connector-card-multi-table-customer-row-text">
              ,
            </span>
          </div>
        )
      })
      
      return (
        <div class="connector-card-multi-table-customer-row">
          { content }
        </div>
      )
    },
    /* 关联工单类型 */
    renderColumnWithRelatedTasks(column: ConnectorField, row: Record<string, any>) {
      
      let tasks: Record<string, any>[] = row?.[column.fieldName || ''] || []
      
      if (isNotArray(tasks)) {
        tasks = [tasks as unknown as Record<string, any>]
      }
      
      const classNames = 'view-detail-btn'
      
      const content = tasks.map((item: Record<string, any>) => {
        return (
          <div class="connector-card-multi-table-task-row-item">
            <div
              class={classNames}
            >
              { item.taskNo }
            </div>
            <span class="connector-card-multi-table-task-row-text">
              ,
            </span>
          </div>
        )
      })
      
      return (
        <div class="connector-card-multi-table-task-row">
          { content }
        </div>
      )
    },
    /* 客户地址 */
    renderColumnWithCustomerAddress(column: ConnectorField, row: Record<string, any>) {
      
      const addressList = row?.[column.fieldName || ''] || []
      const address = (
        isArray(addressList) ? addressList[0] || {} : addressList
      ) || {}
      
      return new TaskAddress(address).toString() || address?.name || ''
    },
    /* 客户联系人 */
    renderColumnWithCustomerLinkman(column: ConnectorField, row: Record<string, any>) {
      
      const linkmanList = row?.[column.fieldName || ''] || []
      const linkman = (
        isArray(linkmanList) ? linkmanList[0] : linkmanList
      ) || {}
      
      const linkmanName = linkman?.name || ''
      
      return (
        <div>
          { linkmanName }
        </div>
      )
    },
    /* 服务部门 */
    renderTag(column: ConnectorField, row: Record<string, any>) {
      
      const tags = row?.[column.fieldName || ''] || []
      const tag = (
        isArray(tags) ? tags[0] : tags
      ) || {}
      
      const tagName = tag?.tagName || tag?.name
      
      return (
        <div>
          { tagName }
        </div>
      )
    },
    /* 地址类型 */
    renderColumnWithAddress(column: ConnectorField, row: Record<string, any>): string {
      const address: any = row?.[column.fieldName || ''] || {}
      return new TaskAddress(address).toString()
    },
    /**
     * @description 渲染 操作
     */
    renderOperation(row: Record<string, any>) {
      return (
        <div>
          { this.showDeleteButton && this.renderOperationDeleteButton(row) }
        </div>
      )
    },
    /**
     * @description 渲染 操作 删除按钮
     */
    renderOperationDeleteButton(row: Record<string, any>) {
      return (
        <el-button
            type="text"
            onClick={() => this.onConnectorCardItemDeleteHandler(row)}
        >
          {t('common.base.delete')}
        </el-button>
      )
    },
  },
  render(h: CreateElement) {
    
    return (
      <p class="option-item-font">
        <label>{this.field.label}：</label>
        <span> { this.renderTableColumnField(h, this.value, this.field) }</span>
      </p>
    )
  }
})
